import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:quick_widget/drop_menu_container.dart';
import 'package:saas_order_meal/net/apis.dart';
import 'package:saas_order_meal/net/net_response/menu/regular_menu_data.dart';
import 'package:saas_order_meal/res/resources.dart';
import 'package:saas_order_meal/saas_order_meal.dart';
import 'package:saas_order_meal/utils/meal_ext_utils.dart';
import 'package:saas_order_meal/viewmodel/elder_month_record_view_model.dart';
import 'package:saas_order_meal/viewmodel/regular_menu_contain_view_model.dart';
import 'package:saas_order_meal/widget/select_item_widget.dart';

import '../model/order_request_data.dart';

class RegularMenuContainWidget extends BaseStatefulMvvmWidget {
  List<RegularMenuData> menuList;
  final OrderRequestData orderData;
  final bool isRegular;

  RegularMenuContainWidget(
      {required this.menuList,
      required this.orderData,
      this.isRegular = false}) {}

  @override
  State<StatefulWidget> createState() => _RegularMenuContainState();
}

class _RegularMenuContainState extends BaseMvvmState<
    RegularMenuContainViewModel, RegularMenuContainWidget> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget? buildLoadingContentView() {
    return Column(
      children: [
        DropMenuContainer(
          controller: viewModel.controller,
          isBottomOut: true,
          child: Row(
            children: [
              SelectItemWidget<RegularMenuData>(
                viewModel.menuList,
                position: viewModel.timeSelection,
                canSelected: (item) {
                  return "";
                  // return item.hasOrderedRemark.isNotEmpty?item.hasOrderedRemark:item.canSelectRemark??"";
                },
                itemBuilder: (context, item, index, selected) {
                  return LeftTimeTypeItemWidget(item, selected);
                },
                onCallback: (index, data) {
                  setState(() {
                    viewModel.timeSelection = index;
                    viewModel.selectTime = data;
                  });
                },
                separatorBuilder: (context, index) {
                  return const SizedBox(
                    height: 20,
                  );
                },
                padding: EdgeInsets.symmetric(vertical: 30),
              ).addToContainer(
                  width: 70, margin: EdgeInsets.symmetric(horizontal: 16)),
              ListView(
                padding: EdgeInsets.symmetric(vertical: 20),
                children:
                    (viewModel.selectTime?.timeSectionList ?? []).map((e) {
                  return Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if ((e.categaryList ?? []).isNotEmpty &&
                          !widget.isRegular) ...[
                        CommonText("${e.categary} 选${e.selectNumber}"),
                        Container(
                          height: 15,
                        )
                      ],
                      ListView(
                        shrinkWrap: true,
                        physics: NeverScrollableScrollPhysics(),
                        children: (e.categaryList ?? [])
                            .map((food) => itemMenuContent(e, food))
                            .toList(),
                      )
                    ],
                  );
                }).toList(),
              ).setWeight(3),
              Container(
                width: 16,
              )
            ],
          ),
        ).setWeight(1),
        bottomPriceWidget()
      ],
    );
  }

  Widget itemMenuContent(
      RegularMenuTimeSectionList data, RegularMenuCategaryList food) {
    return Stack(
      children: [
        Stack(
          children: [
            CachedNetworkImage(
              imageUrl: "${Apis.imageHead}${food.attachIds}",
              width: 90,
              height: 90,
              httpHeaders: ImageLoad.globalHeader,
              placeholder: (context, url) {
                return SaasOrderMeal.foodImagePlaceHold==null?Image.asset(
                  "images/none.png",
                  package: "saas_order_meal",
                  width: 90,
                  height: 90,
                ):Image.asset(
                  SaasOrderMeal.foodImagePlaceHold!,
                  width: 90,
                  height: 90,
                );
              },
              errorWidget: (context, url, error) {
                return SaasOrderMeal.foodImagePlaceHold==null?Image.asset(
                  "images/none.png",
                  package: "saas_order_meal",
                  width: 90,
                  height: 90,
                ):Image.asset(
                  SaasOrderMeal.foodImagePlaceHold!,
                  width: 90,
                  height: 90,
                );
              },
            ).onTap(() async {
              if (!food.disableRemark.isNullOrEmpty()) {
                showToast(food.disableRemark);
                return;
              }
              if (SaasOrderMeal.canChooseMore || widget.isRegular) {
                if (SaasOrderMeal.checkOldTag) {
                  var result = await viewModel.checkTags(food);
                  if (result) {
                    viewModel.addClick(food, data);
                  }
                } else {
                  viewModel.addClick(food, data);
                }
                return;
              }
              setState(() {
                viewModel.multiChooseClick(food, data);
                viewModel.getSelectItem();
              });
            }),
            CommonText(food.goodsName).setLocation(left: 100, top: 4),
            CommonText("¥${food.price?.d}", textColor: Colors.red)
                .setLocation(bottom: 4, left: 100),
            if (!SaasOrderMeal.canChooseMore && !widget.isRegular)
              Row(
                children: [
                  if ((food.status ?? 0) == 1)
                    Icon(
                      Icons.check_circle,
                      color: SaasOrderMeal.mainColor,
                      size: 30,
                    )
                ],
              ).setLocation(bottom: 0, right: 0),
            if (SaasOrderMeal.canChooseMore || widget.isRegular)
              Row(
                children: [
                  if ((food.number ?? 0) > 0)
                    Icon(
                      Icons.remove_circle_outline,
                      color: SaasOrderMeal.mainColor,
                      size: 30,
                    ).onTap(() {
                      viewModel.removeClick(food);
                    }),
                  Container(
                    width: 15,
                  ),
                  if ((food.number ?? 0) > 0)
                    CommonText("${food.number ?? 0}", textSize: 20),
                  Container(
                    width: 15,
                  ),
                  Icon(
                    Icons.add_circle_rounded,
                    color: SaasOrderMeal.mainColor,
                    size: 30,
                  ).onTap(() async {
                    if (SaasOrderMeal.checkOldTag) {
                      var result = await viewModel.checkTags(food);
                      if (result) {
                        viewModel.addClick(food, data);
                      }
                    } else {
                      viewModel.addClick(food, data);
                    }
                  })
                ],
              ).setLocation(bottom: 0, right: 0),
          ],
        ).addToContainer(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
                color: Colors.white, borderRadius: 10.borderRadius)),
        if (!food.disableRemark.isNullOrEmpty())
          Container(
            decoration: BoxDecoration(
                color: Colors.grey.withOpacity(0.5),
                borderRadius: 10.borderRadius),
          ).onTap(() {
            if (!food.disableRemark.isNullOrEmpty()) {
              showToast(food.disableRemark);
              return;
            }
          }).setLocation(left: 0, right: 0, top: 0, bottom: 0)
      ],
    ).onTap(() async {
      if (!food.disableRemark.isNullOrEmpty()) {
        showToast(food.disableRemark);
        return;
      }
      if (SaasOrderMeal.canChooseMore || widget.isRegular) {
        if (SaasOrderMeal.checkOldTag) {
          var result = await viewModel.checkTags(food);
          if (result) {
            viewModel.addClick(food, data);
          }
        } else {
          viewModel.addClick(food, data);
        }
        return;
      }
      setState(() {
        viewModel.multiChooseClick(food, data);
        viewModel.getSelectItem();
      });
    }).addToContainer(
      margin: EdgeInsets.only(bottom: 10),
    );
  }

  Widget bottomPriceWidget({bool clickShopcar = true}) {
    return Stack(
      children: [
        Image.asset(
          "images/shop_car.png",
          width: 40,
          height: 40,
          package: "saas_order_meal",
          color: viewModel.selectedMealList.isEmpty
              ? Colors.black
              : SaasOrderMeal.mainColor,
        ).onTap(() {
          if (viewModel.selectedMealList.isEmpty) {
            return;
          }
          // if (!clickShopcar) {
          //   Go().pop();
          //   return;
          // }
          if (viewModel.controller.isShow) {
            viewModel.controller.hide();
          } else {
            viewModel.controller
                .showDropMenu(menuWidget: viewModel.bottomContent());
          }
          // showSelectBottom();
        }).setLocation(top: 0, bottom: 0, left: 16),
        if (viewModel.selectedMealList.isNotEmpty)
          CommonText("${viewModel.selectedMealList.length}",
                  textColor: Colors.white, textSize: 14)
              .addToContainer(
                  decoration: BoxDecoration(
                      color: Colors.red, borderRadius: 20.borderRadius),
                  alignment: Alignment.center,
                  constraints: BoxConstraints(minHeight: 20, minWidth: 20))
              .setLocation(left: 44, top: 8),
        (orderFoodShowPrice
                ? Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      CommonText("¥", textSize: 16),
                      CommonText((viewModel.totalPrice.d).toString(),
                          textSize: 20)
                    ],
                  )
                : CommonText(""))
            .setLocation(top: 0, bottom: 0, left: 70),
        TextButton(
          onPressed: () {
            viewModel.toApplySubmit();
          },
          child: CommonText('去结算', textColor: Colors.white),
          style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all(
                  viewModel.selectedMealList.isEmpty
                      ? Colors.grey
                      : SaasOrderMeal.mainColor),
              shape: MaterialStateProperty.all(StadiumBorder()),
              fixedSize: MaterialStateProperty.all(Size(90, 40))),
        )
            .addToContainer(alignment: Alignment.center)
            .setLocation(right: 16, top: 0, bottom: 0)
      ],
    ).addToContainer(width: double.infinity, height: 65, color: Colors.white);
  }

  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return loadingContentWidget;
  }

  @override
  RegularMenuContainViewModel createViewModel() {
    return RegularMenuContainViewModel(context,
        menuList: widget.menuList,
        orderData: widget.orderData,
        isRegular: widget.isRegular);
  }

  @override
  void onRetryClick() {}
}
